

# Create your views here.
import json
import random
from itertools import groupby
from operator import itemgetter

import time

import datetime
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.views import APIView
from rest_framework_jwt.views import ObtainJSONWebToken
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from users import constants
from users import serializers
from users.models import User
import base64

from users.serializers import AddUserBrowsingHistorySerializer
from users.utils import storage, generate_verify_email_url, check_verify_email_token
from celery_tasks.emails.tasks import send_verify_email


class UserView(CreateAPIView):
    """
    用户注册
    """
    serializer_class = serializers.CreateUserSerializer


class UserAuthorizeView(ObtainJSONWebToken):
    """
    用户认证
    """
    def post(self, request, *args, **kwargs):
        # 调用父类的方法，获取drf jwt扩展默认的认证用户处理结果
        response = super().post(request, *args, **kwargs)

        # 此处预留未来可能出现的登陆附加操作
        return response


class UserDetailView(RetrieveAPIView):
    """
    用户详情
    """
    serializer_class = serializers.UserDetailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


class UserPartInfoView(RetrieveAPIView):
    """
    用户部分信息
    id
    username
    avatar_url
    """
    serializer_class = serializers.UserPartInfoSerializer

    def get_queryset(self):
        pk = self.kwargs['pk']
        return User.objects.filter(pk=pk)


class MobileCountView(APIView):
    """
    手机号数量
    """
    def get(self, request, mobile):
        """
        获取指定手机号数量
        """
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count
        }

        return Response(data)


class SMSCodeView(APIView):
    """
    短信验证码
    """
    def get(self, request, mobile):
        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        print('短信验证码:', sms_code)

        # 保存短信验证码  保存发送记录
        redis_conn = get_redis_connection('verify_codes')

        # redis管道
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # 让管道通知redis执行命令
        pl.execute()

        return Response({'message': 'OK', 'yzm': sms_code})


class UserUpdateUserView(UpdateAPIView):
    """
    修改用户数据
    """
    serializer_class = serializers.UserUpdateUser
    permission_classes = [IsAuthenticated]

    def get_object(self, *args, **kwargs):
        if self.request.data.get('avatar_base64'):
            avatar_data = self.request.data['avatar_base64'].split(',')[1]
            url = storage(base64.b64decode(avatar_data))
            self.request.user.avatar_url = 'http://pns4r9vpo.bkt.clouddn.com/' + url
        return self.request.user


class SendEmailView(APIView):
    """发送验证邮件"""
    permission_classes = [IsAuthenticated]

    def post(self,request):
        # 获取输入的邮箱
        email = request.user.email
        data = {
            'user_id': request.user.id,
            'email': email
        }
        # 生成验证链接
        verify_url = generate_verify_email_url(data)
        # 发送验证邮件
        send_verify_email.delay(email, verify_url)
        return Response({'msg': '验证邮件已发送，请前往邮箱进行验证'}, status=status.HTTP_201_CREATED)


class VerifyEmailView(APIView):
    """
    邮箱验证
    """
    def get(self, request):
        # 获取token
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)

        # 验证token
        user = check_verify_email_token(token)
        if user is None:
            return Response({'message': '链接信息无效'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            user.email_active = 1
            user.save()
            return Response({'message': 'OK'})


class UserBrowsingHistoryView(CreateAPIView):
    """
    用户浏览历史记录
    """
    serializer_class = AddUserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """
        获取
        """
        user_id = request.user.id

        redis_conn = get_redis_connection("history")
        history_list = redis_conn.lrange("history_%s" % user_id, 0, constants.USER_BROWSE_HISTORY_MAX_LIMIT-1)

        history = []
        history_data = []
        j = 0
        for i in history_list:
            history.append(dict(json.loads(i.decode())))

        # 按时间降序排序
        history.sort(key=itemgetter('create_date'), reverse=True)

        # 获取今天和昨天
        now = time.localtime(time.time())
        now_time = datetime.datetime.now()
        yes_time = now_time + datetime.timedelta(days=-1)
        today = time.strftime("%Y-%m-%d", now)
        yesterday = yes_time.strftime("%Y-%m-%d")

        # 分组
        for create_date, items in groupby(history, key=itemgetter('create_date')):
            new_data = create_date
            if new_data == today:
                new_data = '今天'
            if new_data == yesterday:
                new_data = '昨天'
            history_data.append({'create_date': new_data, 'data': []})
            for i in items:
                history_data[j]['data'].append(i)
            j += 1

        print(history_data)
        return Response(history_data)
